<?php
namespace app\admin\controller\recharge;

use app\common\controller\Backend;
use think\Controller;
use fast\Http;
use think\Config;
use think\Log;
use think\Db;
use app\admin\model\Order;
use app\admin\model\YOnlineorder;
use app\admin\model\YOrdergoods;
use app\admin\model\YOrderlog;
use think\Exception;
use app\admin\model\SGoods;
use app\admin\model\YPromotionincome;
use app\admin\model\YAgency;
use function EasyWeChat\Payment\get_client_ip;

//api对外调用控制器
require_once("pcfunc.php");

//个人自定义配置文件在extra backstage中;
class Api extends Backend
{   

    protected $goodsconfig = [];
    public function _initialize($options = [])
    {   
		//获取配置文件
		$this->GameDBConfig = Config::get('GameDB'); 		// 获取游戏服务器的IP地址等信息
		$this->DatabaseConfig = Config::get('database'); 	//获取数据库连接.
		$this->ApikeyConfig = Config::get('Apikey');		//key配置
        /**
         * 跨域设置
         */
        header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求 
        header('Access-Control-Allow-Methods:PUT,POST,GET,DELETE,OPTIONS');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); 
        $this->goodsconfig = require_once('goodscnf.php');  //商品配置

    }

	//获取订单接口
    public function Getorder()
    {   
        $data = $_GET;
        if (empty($data)||empty($data['uid']) || empty($data['goodsId']) || empty($data['goodsName']) || empty($data['goodsDes']) || empty($data['goodsNum'])) 
        {   
            return resError("Getorder 参数不能为空");
        }       
        
        $datatime =  getMillisecond();                                                   //获取创建时间戳
        $oinfo =[
        'code'      => '0',                                                             //返回code 0为创建成功,非0为失败，则获取msg消息错误。
        'uid'       => $data['uid'],                                                   //用户id
        'goodsId'   => $data['goodsId'],                                              //商品id
        'goodsName' => $data['goodsName'],                                              //商品名称
        'goodsDes'  => isset($data['goodsDes']) ? $data['goodsDes'] : '',               //穿透参数(可扩展)
        'goodsNum'  => $data['goodsNum'],                                               //商品数量
        'payType'   => $data['payType'],                                                //支付类型
        'createdate'=> $datatime,                                                       //创建时间
        'ordersid'  => $data['uid'].$datatime,                                          //生成订单号
        'goodsprice'=> $this->goodsconfig[$data['goodsId']]['money'],                   //获取价格
        ];



        //构造数据语句
        $Dbdata = [
        'ordersid' => $oinfo['ordersid'], 
        'uid' => $oinfo['uid'],
        'goodsId'=>$oinfo['goodsId'],
        'goodsName'=>$oinfo['goodsName'],
        'goodsNum'=>$oinfo['goodsNum'],
        'goodsprice'=>$oinfo['goodsprice'],
        'paytype'=>$oinfo['payType'],
        'createdate'=>$oinfo['createdate'],
        ];

        //写入数据库
        $this->addTbale($this->DatabaseConfig,'fa_v_orders',$Dbdata);
     
        //回调返回订单
        return json_encode($oinfo);

    }

	//提供给爱上调用的接口
    public function AisCallback()
    {   
        $data = $_POST;
        if (empty($data)||empty($data['subject']) ||  empty($data['amount']) ||empty($data['channel']) || empty($data['pay_order_id']) || empty($data['trade_status']) || empty($data['order_paydt']) || empty($data['extra_common_param'])) 
        {  
		   Log::record($data,'error');
           return resError("AisCallback 参数不能为空");
        }

        $extra_common_param = json_decode($data['extra_common_param'],true);

        $oinfo =[                                                       
        'uid'           => $extra_common_param['uid'],              //用户id
        'goodsName'     => $data['subject'],                        //商品名字 
        'goodsprice'    => $data['amount'],                         //商品价格                             
        'payType'       => $data['channel'],                        //支付类型
        'pay_order_id'  => $data['pay_order_id'],                   //支付订单
        'status'        => $data['trade_status'],                   //充值状态 1成功
        'ordersid'      => $extra_common_param['ordersid'],         //订单id
        'paytime'       => $data['order_paydt'],                    //支付时间
        ];


        //构造查询语句
        $where = "ordersid = $oinfo[ordersid]";
        $dbdata = $this->selectTbale($this->DatabaseConfig,'fa_v_orders',$where);           //获取数据库订单
        if(empty($dbdata))
        {
             return resError("该订单号不存在");
        }

        //订单对比
        if(ordersidbeff($oinfo,$dbdata))
        {   
            return resError("Invalid order data exception");
        }

        //验证合法性
        //$data['sign'] == asHmacMd5(json_encode($data),$this->config['Apikey']['Aiskey']) &&
        if($data['trade_status'] == '1')
        {   
             $Sreq = [];
             $Sreq['uid'] = $oinfo['uid'];                                                                              //玩家Id
             $Sreq['diamond'] = $this->goodsconfig[$dbdata[0]['goodsId']]['diamond'];                                         //钻石数量
             $Sreq['ordersid'] = $oinfo['ordersid'];                                                                    //订单id
             $Sreq['sign'] = strtoupper(md5($Sreq['uid'].$Sreq['diamond'].$Sreq['ordersid'].$this->ApikeyConfig['Gamekey']));  //签名参数

            //构造条件
            $find = "ordersid = $oinfo[ordersid]";

            //更新内容;
            $up = [
            'paytime' => $oinfo['paytime'], 
            'status' => $oinfo['status'],
            'pay_order_id'=>$oinfo['pay_order_id'],
            ];

            //更新数据库
            if($this->updataTbale($this->DatabaseConfig,'fa_v_orders',$find,$up))
            {
               return resError("不存在订单或者订单已经使用过");
            }

            //发送给游戏服务器
            if(empty(Http::get($this->GameDBConfig['api_url'].'recharge',$Sreq)))
             {	 
				 Log::err('服务器返回充值失败');
                 return 'Recharge failed';
             }

             return 'success';
        }
        
             return '验证未通过';
    }

    //获取游戏服务器Ip地址
    public function GetServerIp()
    {
        $data = $_GET;
        if (empty($data))
        {
            return resError("无此gsid");
        }
    
    
        //根据帐号获取uid
        $retData = $this->selectTbale($this->DatabaseConfig,'fa_v_gamelist')[($data['gsid'] == 'undefined' || empty($data['gsid']))? 0 : $data['gsid'] - 1 ];
		
        //获取服务器状态,当游戏服务器，开机状态，则把限制登录的权利给游戏服务器，关闭后台来控制
        if(empty($retData)||$retData['status'] == 'close')
        {
            if(!empty(Http::get($this->GameDBConfig['api_url'].'ping')))
            {
                $retData['code'] = 0;
            }else{
                $retData['code'] = 1;
            }
        }else{
            $retData['code'] = 0;
        }
    
        return json_encode($retData);
    }
	
    //身份证绑定http://192.168.88.155/admin/recharge/Api/SetIdzcsdk?uid=112&Name=周杰伦&idNo=100000
    public function SetIdzcsdk()
    {   
        $data = $_POST;
        if (empty($data)||empty($data['uid'])||empty($data['Name'])||empty($data['idNo'])) 
        {   
                 return resError('参数不能为空！');
        }

        //更新内容;
        $updata = [
        'name' => $data['Name'], 
        'ID' => $data['idNo'],
        ];
        $where = "uid = $data[uid]";
         //更新数据库
        if($this->updataTbale($this->GameDBConfig,'user',$where,$updata))
        {
            return resError('绑定身份证失败，没有该id玩家或已绑定无需重复绑定');
        }
        return resoK();
    }
    

    //用户反馈http://192.168.88.155/admin/recharge/Api/userfeedback?uid=2011&phone=15802346778&content=这个游戏非常卡
    public function userfeedback()
    {   

        $data = $_POST;
        if (empty($data) || empty($data['uid']) || empty($data['content']))
        {   
            return resError("参数不能为空！");
        }

        //获取玩家nickname
        $where = "uid = $data[uid]";
        $sdata = $this->selectTbale($this->GameDBConfig,'user',$where,'uid,nickname');
        if (empty($sdata)) 
        {
            return resError('错误的玩家ID');    
        }
         //构造数据语句
        $adddata = [
        'createtime'=>time(),
        'uid' => $data['uid'],
        'nickname'=>$sdata[0]['nickname'],
        'phone'=>isset($data['phone']) ? $data['phone'] : '',
        'content'=>$data['content'],
        ];

        //写入数据库
        $this->addTbale($this->DatabaseConfig,'fa_v_feedback',$adddata);

        return resoK();
    }

    //页面获取游戏规则 http://192.168.88.155/admin/recharge/Api/userfeedback?uid=2011&phone=15802346778&content=这个游戏非常卡
    public function gamerule()
    {   
        $data = $_GET;
        //$data = $_POST;
        if (empty($data) || empty($data['']) || empty($data['content']))
        {   
                 return resError("参数不能为空！");
        }

        //获取玩家nickname
        $where = "uid = $data[uid]";
        $sdata = $this->selectTbale($this->GameDBConfig,'user',$where,'uid,nickname');
        if (empty($sdata)) 
        {
            return resError('错误的玩家ID');    
        }

        return resoK();
    }

    //获取页面地址http://192.168.88.155/admin/recharge/Api/getresources
    public function Getresources()
    {   
        //所有的规则url
        $sdata = $this->selectTbale($this->DatabaseConfig,'fa_v_webpact');
        if (empty($sdata)) 
        {
            return resError('错误的玩家ID');    
        }
        return json_encode($sdata);
    }

    //代理充值 http://192.168.88.155/admin/recharge/Api/proxyrecharge?uid=2011&auid=15802346778&cardnum=这个游戏非常卡
    public function proxyrecharge()
    {
        $data = $_POST;

        //验证是否为空.
        if(empty($data) || empty($data['uid'])|| empty($data['target']) || empty($data['cardnum']) || empty($data['sign']))
        {   
            return resError("参数不能为空");
        }

        //签名验证
        $sign = strtoupper(md5($data['uid'].$data['target'].$data['cardnum'].$data['agetype'].$this->ApikeyConfig['Gamekey']));

        if($sign != $data['sign'])
        {   
            return resError('签名错误');
        }

        $sreq = [
            'uid' => $data['uid'],
            'target' => $data['target'],
            'diamond' => $data['cardnum'],
            'agetype' => $data['agetype'],
            'sign' => $data['sign'],
        ];

        //发送给游戏服务器
        if(Http::get($this->GameDBConfig['api_url'].'agencyRecharge',$sreq) == 'ok')
        {   
			return resoK();
        }
		
        return resError("充值失败");
    }

    //更新版本
    public function Geteversion()
    {	
		$data =$_GET;
		if(empty($data)||empty($data['ip']))
		{
			 return resError('无ip地址');    
		}
        $where = "status = 'geton'";
       //所有的规则url
        $dbdata = $this->selectTbale($this->DatabaseConfig,'fa_v_version',$where,'*');
		//验证是否打开,当长度大于1，表示有多个更新地址开启
		if(sizeof($dbdata)>1)
		{
			//查询ip地址，是否是白名单的ip地址，如果是，则开放
			$Userip = $this->selectTbale($this->DatabaseConfig,'fa_v_testip',"ip='".$data['ip']."'",'*');
			if(!empty($Userip))
			{
				return json_encode($dbdata[1]);
			}
		}
	
        if (empty($dbdata)) 
        {
            return resError('没有更新版本');    
        }
		
        return json_encode($dbdata[0]);
    }


    //客户端错误日志
    public function ClientLog()
    {
        $data =$_GET;
        //构造数据语句
        $addData = [
			'createtime'=>time(),
			'uid' => $data['uid'],
			'nickname'=>$data['nickname'],
			'content'=>$data['content'],
        ];
		
		//白名单验证
		$whiteinfo = $this->selectTbale($this->DatabaseConfig,'fa_v_whitelist','uid = '.$data['uid']); 
		if(empty($whiteinfo))
		{   
			 //获取最后一条写入记录的时间.与当前的时间进行比较
			 if (!empty($this->selectTbale($this->DatabaseConfig,'fa_v_clientlog',"UNIX_TIMESTAMP(date_sub(now(),interval 120 second)) < createtime and uid = $data[uid]")))
			 {	
				return;
			 }			 
		}
        //写入数据库
        $this->addTbale($this->DatabaseConfig,'fa_v_clientlog',$addData);
		
    }
	
	//登录数获取.
	public function GetLogindata()
	{		
		//Db::connect("DB_Config_1")->name("test")->select();			
		//获取登录数
		return Db::query("select FROM_UNIXTIME(logintime/1000,'%m.%d') AS hours ,count(uid) AS amount from `fa_v_loginrecord`  where date_sub(curdate(), INTERVAL 30 DAY) <= date(FROM_UNIXTIME(`logintime`/1000))  GROUP BY hours");
			
	}
	
	//注册数获取.
	public function Getloggingdata()
	{
		return Db::connect("GameDB")->query("select FROM_UNIXTIME(createTime/1000,'%m.%d') AS hours ,count(uid) AS amount from `user`  where date_sub(curdate(), INTERVAL 30 DAY) <= date(FROM_UNIXTIME(`createTime`/1000))  GROUP BY hours");
	
	}
	
	//获取开房数据统计.
	//做之前，需要修改，开房记录和游戏记录的表存储
	public function GetOpenroomdata()
	{		
			
			//$std = $this->selectcount($this->DatabaseConfig,'fa_v_annal_room',"status = 'gameover' and date_sub(curdate(), INTERVAL 7 DAY) <= date(FROM_UNIXTIME(`createtime`/1000))  GROUP BY hours,kinId","FROM_UNIXTIME(createtime/1000,'%Y-%m-%d') AS hours ,kinId,count(uid)"); //今日开房数
			$Querarr = Db::query("select FROM_UNIXTIME(createtime/1000,'%m.%d') AS hours ,kinId,count(uid) AS amount from `fa_v_annal_room`  where status = 'gameover' and date_sub(curdate(), INTERVAL 30 DAY) <= date(FROM_UNIXTIME(`createtime`/1000))  GROUP BY hours,kinId");
			
			$arr =[];
			
			//提取时间构造结构
			foreach($Querarr as &$value)
			{	
				$Larr = [];
				//如果为false则加入，数组。
				$yesN = false;
				if (!empty($arr)){
					foreach($arr as &$arrv)
					{
						if($arrv['time'] === $value['hours'])
						$yesN = true;
					}
				}
				if($yesN == false)
				{
					$Larr['time'] = $value['hours'];
					$Larr['client'] = 0;
					array_push($arr,$Larr);
				}
			}
			
			//提取数据
			foreach($Querarr as &$value)
			{	
				for($i=0;$i<count($arr);$i++)
				{
					//如果相等则把value的值判断是那个游戏类型，加入数据
					if($arr[$i]['time'] === $value['hours'])
					{	
						switch($value['kinId'])
						{
							case 100://血战到底
								$arr[$i]['game100'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount'];  
								break;
							case 120://万州麻将
								$arr[$i]['game120'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
							case 121://万州幺鸡代
								$arr[$i]['game121'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
							case 122://万州幺鸡落地
								$arr[$i]['game122'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
							case 320://拼三张
								$arr[$i]['game320'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
							case 340://牛牛
								$arr[$i]['game340'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
						}
					}
				}
			}
			
			return $arr;
	}
	
	//获取房卡消耗统计
	public function Getroomdeplete()
	{	
	
			//$std = $this->selectcount($this->DatabaseConfig,'fa_v_annal_room',"status = 'gameover' and date_sub(curdate(), INTERVAL 7 DAY) <= date(FROM_UNIXTIME(`createtime`/1000))  GROUP BY hours,kinId","FROM_UNIXTIME(createtime/1000,'%Y-%m-%d') AS hours ,kinId,count(uid)"); //今日开房数
			$Querarr = Db::query("select FROM_UNIXTIME(createtime/1000,'%m.%d') AS hours ,kinId,sum(roomcode) AS amount from `fa_v_annal_room`  where status = 'gameover' and date_sub(curdate(), INTERVAL 30 DAY) <= date(FROM_UNIXTIME(`createtime`/1000)) GROUP BY hours,kinId");
			
			$arr =[];
			
			//提取时间构造结构
			foreach($Querarr as &$value)
			{	
				$Larr = [];
				//如果为false则加入，数组。
				$yesN = false;
				if (!empty($arr)){
					foreach($arr as &$arrv)
					{
						if($arrv['time'] === $value['hours'])
						$yesN = true;
					}
				}
				if($yesN == false)
				{
					$Larr['time'] = $value['hours'];
					$Larr['client'] = 0;
					array_push($arr,$Larr);
				}
			}
			
			//提取数据
			foreach($Querarr as &$value)
			{	
				for($i=0;$i<count($arr);$i++)
				{
					//如果相等则把value的值判断是那个游戏类型，加入数据
					if($arr[$i]['time'] === $value['hours'])
					{	
						switch($value['kinId'])
						{
							case 100://血战到底
								$arr[$i]['game100'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount'];  
								break;
							case 120://万州麻将
								$arr[$i]['game120'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
							case 121://万州幺鸡代
								$arr[$i]['game121'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
							case 122://万州幺鸡落地
								$arr[$i]['game122'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
							case 320://拼三张
								$arr[$i]['game320'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
							case 340://牛牛
								$arr[$i]['game340'] = $value['amount'];
								$arr[$i]['client'] = $arr[$i]['client'] + $value['amount']; 
								break;
						}
					}
				}
			}
			
			return $arr;
	}
	
	//获取在线数据统计
	public function GetOnlinedata()
	{
		//Db::connect("DB_Config_1")->name("test")->select();			
		//获取登录数
		
		$arr = Db::query("select * from `fa_v_onlineinfo` where date_sub(curdate(), INTERVAL 30 DAY) <= date(FROM_UNIXTIME(`createtime`/1000))");
		if(empty($arr))
		{
			return '';
		}
		
		$jarr = json_decode($arr[0]['online'],true);
		
		for($i = 0;$i<count($jarr);$i++)
		{
			$jarr[$i]['time'] = date('H:i:s', $jarr[$i]['time']);
		}
		return json_encode($jarr,true);
	}
	
	//游戏实时获取占比
	//只可用于js调用
	public function proportion()
	{
	
		//获取游戏中房间数量.
		$gameroomlist = json_decode(Http::get($this->GameDBConfig['api_url'].'gamingUser'),TRUE);
		//获取在线人数
		$onlineUsers = Http::get($this->GameDBConfig['api_url'].'onlineUsers');
		//提取数据
		$arr['builderJson'] =[];
		$arr['builderJson']['roomCount'] = 0;
		$arr['builderJson']['userCount'] = 0;
		$arr['downloadJson'] =[];
		$arr['themeJson'] = [];
		$arr['onlineUsers'] = isset($onlineUsers) ? $onlineUsers : '0';
		if(!empty($gameroomlist))
		foreach ($gameroomlist as $key => $value)
		{	
			switch($key){
				case 100:
					$arr['builderJson']['charts']['血战到底'] = $value['userCount']; //游戏中的人数
					$arr['builderJson']['components']['血战到底'] = $value['roomCount']; //开房数
					//获取开房占比
					if($arr['builderJson']['charts']['血战到底'] > 0)
					$arr['downloadJson']['血战到底'] = $value['roomCount'];				 //开房总数
					if($arr['builderJson']['components']['血战到底'] > 0)
					$arr['themeJson']['血战到底'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;   // 跳出循环
				case 120:
					$arr['builderJson']['charts']['万州麻将'] = $value['userCount'];
					$arr['builderJson']['components']['万州麻将'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['万州麻将'] > 0)
					$arr['downloadJson']['万州麻将'] = $value['roomCount'];
					if($arr['builderJson']['components']['万州麻将'] > 0)
					$arr['themeJson']['万州麻将'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;
				case 121:
					$arr['builderJson']['charts']['幺鸡代'] = $value['userCount'];
					$arr['builderJson']['components']['幺鸡代'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['幺鸡代'] > 0)
					$arr['downloadJson']['幺鸡代'] = $value['roomCount'];
					if($arr['builderJson']['components']['幺鸡代'] > 0)
					$arr['themeJson']['幺鸡代'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;
				case 122:
					$arr['builderJson']['charts']['幺鸡落地'] = $value['userCount'];
					$arr['builderJson']['components']['幺鸡落地'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['幺鸡落地'] > 0)
					$arr['downloadJson']['幺鸡落地'] = $value['roomCount'];
					if($arr['builderJson']['components']['幺鸡落地'] > 0)
					$arr['themeJson']['幺鸡落地'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;	
				case 140:
					$arr['builderJson']['charts']['广安麻将'] = $value['userCount'];
					$arr['builderJson']['components']['广安麻将'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['广安麻将'] > 0)
					$arr['downloadJson']['广安麻将'] = $value['roomCount'];
					if($arr['builderJson']['components']['广安麻将'] > 0)
					$arr['themeJson']['广安麻将'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;	
				case 160:
					$arr['builderJson']['charts']['扣点点'] = $value['userCount'];
					$arr['builderJson']['components']['扣点点'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['扣点点'] > 0)
					$arr['downloadJson']['扣点点'] = $value['roomCount'];
					if($arr['builderJson']['components']['扣点点'] > 0)
					$arr['themeJson']['扣点点'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;	
				case 170:
					$arr['builderJson']['charts']['推倒胡'] = $value['userCount'];
					$arr['builderJson']['components']['推倒胡'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['推倒胡'] > 0)
					$arr['downloadJson']['推倒胡'] = $value['roomCount'];
					if($arr['builderJson']['components']['推倒胡'] > 0)
					$arr['themeJson']['推倒胡'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;	
				case 190:
					$arr['builderJson']['charts']['呼伦贝尔'] = $value['userCount'];
					$arr['builderJson']['components']['呼伦贝尔'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['呼伦贝尔'] > 0)
					$arr['downloadJson']['呼伦贝尔'] = $value['roomCount'];
					if($arr['builderJson']['components']['呼伦贝尔'] > 0)
					$arr['themeJson']['呼伦贝尔'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;
				case 300:
					$arr['builderJson']['charts']['斗地主'] = $value['userCount'];
					$arr['builderJson']['components']['斗地主'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['斗地主'] > 0)
					$arr['downloadJson']['斗地主'] = $value['roomCount'];
					if($arr['builderJson']['components']['斗地主'] > 0)
					$arr['themeJson']['斗地主'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;
				case 320:
					$arr['builderJson']['charts']['拼三张'] = $value['userCount'];
					$arr['builderJson']['components']['拼三张'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['拼三张'] > 0)
					$arr['downloadJson']['拼三张'] = $value['roomCount'];
					if($arr['builderJson']['components']['拼三张'] > 0)
					$arr['themeJson']['拼三张'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;
				case 340:
					$arr['builderJson']['charts']['牛牛'] = $value['userCount'];
					$arr['builderJson']['components']['牛牛'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['牛牛'] > 0)
					$arr['downloadJson']['牛牛'] = $value['roomCount'];
					if($arr['builderJson']['components']['牛牛'] > 0)
					$arr['themeJson']['牛牛'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;
				case 360:
					$arr['builderJson']['charts']['三公'] = $value['userCount'];
					$arr['builderJson']['components']['三公'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['三公'] > 0)
					$arr['downloadJson']['三公'] = $value['roomCount'];
					if($arr['builderJson']['components']['三公'] > 0)
					$arr['themeJson']['三公'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;
				case 380:
					$arr['builderJson']['charts']['掷骰子'] = $value['userCount'];
					$arr['builderJson']['components']['掷骰子'] = $value['roomCount'];
					//获取开房占比
					if($arr['builderJson']['charts']['掷骰子'] > 0)
					$arr['downloadJson']['掷骰子'] = $value['roomCount'];
					if($arr['builderJson']['components']['掷骰子'] > 0)
					$arr['themeJson']['掷骰子'] = $value['userCount'];
					$arr['builderJson']['roomCount'] += $value['roomCount'];
					$arr['builderJson']['userCount'] += $value['userCount'];
					break;			
			}
		}	
		return $arr;
	}
	
	//只可用于js调用
	//获取游戏中房间数量 在线人数，
	public function GetgamingUser()
	{
			//获取游戏中房间数量.
			$gameroomlist = json_decode(Http::get($this->GameDBConfig['api_url'].'gamingUser'),TRUE);
			
			 //获取在线人数
			$online['onlineUsers'] = Http::get($this->GameDBConfig['api_url'].'onlineUsers');
			$arr =[];
			if(empty($gameroomlist))
			{
				return;
			}
			foreach ($gameroomlist as $key => $value)
			{	
				//if($value['userCount'] == 0 && $value['roomCount'] == 0)
				//continue;
				switch($key){
					case 100:
						$arr['血战到底']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['血战到底']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 120:
					    if($_SERVER['HTTP_HOST'] == 'sjht.zcc9.com'){
					        $arr['城口麻将']['userCount'] = $value['userCount']; //游戏中的人数
					        $arr['城口麻将']['roomCount'] = $value['roomCount']; //开房数
					    }else{
					        $arr['万州麻将']['userCount'] = $value['userCount']; //游戏中的人数
					        $arr['万州麻将']['roomCount'] = $value['roomCount']; //开房数
					    }
						continue;
					case 121:
						$arr['幺鸡代']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['幺鸡代']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 122:
						$arr['幺鸡落地']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['幺鸡落地']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 140:
						$arr['广安麻将']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['广安麻将']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 160:
						$arr['扣点点']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['扣点点']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 170:
						$arr['推倒胡']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['推倒胡']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 190:
						$arr['呼伦贝尔']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['呼伦贝尔']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 210:
					    $arr['桃源泰来麻将']['userCount'] = $value['userCount']; //游戏中的人数
					    $arr['桃源泰来麻将']['roomCount'] = $value['roomCount']; //开房数
					    continue;
					case 270:
					    $arr['宜宾麻将']['userCount'] = $value['userCount']; //游戏中的人数
					    $arr['宜宾麻将']['roomCount'] = $value['roomCount']; //开房数
					    continue;
					case 300:
						$arr['斗地主']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['斗地主']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 320:
						$arr['拼三张']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['拼三张']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 340:
						$arr['牛牛']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['牛牛']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 341:
					    $arr['十人明牌牛牛']['userCount'] = $value['userCount']; //游戏中的人数
					    $arr['十人明牌牛牛']['roomCount'] = $value['roomCount']; //开房数
					    continue;
					case 360:
						$arr['三公']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['三公']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 380:
						$arr['掷骰子']['userCount'] = $value['userCount']; //游戏中的人数
						$arr['掷骰子']['roomCount'] = $value['roomCount']; //开房数
						continue;
					case 400:
					    $arr['关牌']['userCount'] = $value['userCount']; //游戏中的人数
					    $arr['关牌']['roomCount'] = $value['roomCount']; //开房数
					    continue;
    			    case 410:
    			        $arr['宜宾跑得快']['userCount'] = $value['userCount']; //游戏中的人数
    			        $arr['宜宾跑得快']['roomCount'] = $value['roomCount']; //开房数
    			        continue;
				}
				
			}
			
			//统计游戏中的房间数和游戏中的人数
			$count['总计'] = [];
			$count['总计']['userCount'] = 0;
			$count['总计']['roomCount'] = 0;
			foreach ($arr as $key => $value)
			{
				$count['总计']['userCount']+= $value['userCount'];
				$count['总计']['roomCount']+= $value['roomCount'];
			}
			$arr['总计'] = $count['总计'];
			
			$online['room'] = $arr;
		return $online;
	}
	
	/**
	 * 支付充值
	 * @author violet 
	 */
	public function paymentcharge()
	{
	    $data = $_POST;

	    //验证是否为空.
	    if(empty($data))
	    {
	        return resError("参数不能为空");
	    }
	    if(empty($data['uid']))
	    {
	        return resError("uid不能为空");
	    }
	    if(empty($data['orderID']))
	    {
	        return resError("orderID不能为空");
	    }
	    if(empty($data['cardnum']))
	    {
	        return resError("cardnum不能为空");
	    }
	    if(empty($data['sign']))
	    {
	        return resError("sign不能为空");
	    }
	
	    //签名验证
	    $sign = strtoupper(md5($data['uid'].$data['cardnum'].$data['orderID'].$this->ApikeyConfig['Gamekey']));  //签名参数
	
	    if($sign != $data['sign'])
	    {
	        return resError('签名错误');
	    }
	    
	    $sreq = [
	        'uid' => $data['uid'],//玩家ID
	        'diamond' => $data['cardnum'],//房卡数量
	        'ordersid' => $data['orderID'],//订单号
	        'sign' => $data['sign'],//签名参数
	    ];
	    
	    //发送给游戏服务器
	    if(Http::get($this->GameDBConfig['api_url'].'recharge',$sreq) != 'ok' )
	    {
	        Log::err('服务器返回充值失败');
	        return resError('充值失败');
	    }
	     
	    return resoK();
	}
	
	/**
	 * 新增代理时通知游戏服务器
	 * @author violet
	 * @since 2017-12-5
	 */
	public function addAgency()
	{
	    
	    $data = $_POST;
	
	    //验证是否为空.
	    if(empty($data))
	    {
	        return resError("参数不能为空");
	    }
	    if(empty($data['uid']))
	    {
	        return resError("uid不能为空");
	    }
	    if(empty($data['code']))
	    {
	        return resError("code不能为空");
	    }

	    //发送给游戏服务器
	    if(Http::get($this->GameDBConfig['api_url'].'updateAgency',$data)  != 'ok')
	    {
	        return resError('通知失败');
	    }
	
	    return resoK();
	}
	
	/**
	 * 客户端下单
	 * @author violet
	 * @since 2017-11-27
	 */
	public function orderAdd(){
	    
// 	    if($_SERVER['REMOTE_ADDR']){
// 	        $ip = $_SERVER['REMOTE_ADDR'];
// 	    }elseif(getenv('REMOTE_ADDR')){
// 	        $ip = getenv('REMOTE_ADDR');
// 	    }else{
// 	        $ip = 'unknown';
// 	    }
	    
	    $ip = get_client_ip();

	    //基本信息判断 
	    $data = $_GET;
	    if(!isset($data['uid']) || !isset($data['goods_id']) || !isset($data['payment']) || !isset($data['goodsnum']) || !isset($data['sign'])){
	        return resError('游戏ID，商品ID，支付方式，数量，签名 必须选择');
	    }
	    $data['goodsnum'] = (int)$data['goodsnum'];
	    if($data['goodsnum'] < 1){
	        return resError('数量必须为正整数');
	    }
	    if(!in_array($data['payment'], array(0,1,2,3))){
	        return resError('支付方式不合理');
	    }
	    $good_info = Db::table('fa_s_goods')->where(['id'=>$data['goods_id']])->find();//商品信息
        if(empty($good_info)){
            return resError('必须为有效的商品ID');
        }
        $where = "uid = $data[uid]";
        $user_info = $this->selectTbale($this->GameDBConfig,'user',$where,'uid,nickname,diamond');//用户信息
        if(empty($user_info)){
            return resError('必须为有效的游戏ID');
        }
        $sign = strtoupper(md5($data['payment'].$data['uid'].$data['goods_id'].$data['goodsnum'].Config::get('Paykey.clientkey')));
        if($sign !== $data['sign']){
            return resError('签名没通过');
        }
        $code_info = Db::table('fa_y_userinvitationcode')->where(['uid'=>$data['uid']])->find();//邀请码信息
        
        //生成订单
        $orderID = getOrderID($data['payment']);//生成订单编号
	    $obj_order = new YOnlineorder();
	    $obj_order->orderID = $orderID;//订单编号
	    $obj_order->uid = $data['uid'];//游戏ID
	    $obj_order->orderamount = $good_info['price']*$data['goodsnum'];//订单金额
	    $obj_order->addtime = getMillisecond();//下单时间
	    $obj_order->status = 0;//未支付
	    $obj_order->payment = $data['payment'];//支付方式
	    $obj_order->channel = 2;//客户端
	    $obj_order->isgame = 0;//游戏服务器没有添加房卡数
	    $obj_order->ip = $ip;//客户端IP地址
	    if($obj_order->save() == false){
	        return resError('下单失败，请重试');
	    }
	    
	    //订单与商品关系表
	    $obj_goods = new YOrdergoods();
	    $obj_goods->oid = $obj_order->ID;//订单ID
	    $obj_goods->goodsid = $good_info['id'];//商品ID
	    $obj_goods->goodsname = $good_info['name'];//商品名称
	    $obj_goods->goodsprice = $good_info['price'];//商品单价
	    $obj_goods->goodsnum = $data['goodsnum'];//商品数量
	    $obj_goods->totalprice = $good_info['price']*$data['goodsnum'];//商品总价
	    if(!empty($code_info)){
	        $obj_goods->giveid = $good_info['id'];//赠送ID
	        $obj_goods->givenum = $good_info['give'];//赠送额度
	    }else{
	        $obj_goods->giveid = 0;//赠送ID
	        $obj_goods->givenum = 0;//赠送额度
	    }
	    $obj_goods->quotanum = $good_info['quota'];//额度
	    if($obj_goods->save() == false){
	        $obj_order->where(['ID'=>$obj_order['ID']])->delete();//删除订单信息
	        return resError('订单商品关系失败，请重试');
	    }
	    
	    //订单与数量关系表
	    $obj_log = new YOrderlog();
	    $obj_log->oid = $obj_order->ID;//订单ID
	    $obj_log->bfnum = $user_info[0]['diamond'];//下单前数量
	    if($obj_log->save() == false){
	        $obj_goods->where(['oid'=>$obj_order['ID']])->delete();//删除订单商品信息
	        $obj_order->where(['ID'=>$obj_order['ID']])->delete();//删除订单信息
	        return resError('订单商品关系失败，请重试');
	    }
	    
	    $req=[];
	    $req['code'] = 0;
	    $req['data']['orderID'] = $obj_order->orderID;//订单编号
	    $req['data']['orderamount'] = $obj_order->orderamount;//订单金额
	    $req['data']['uid'] = $data['uid'];//游戏ID
// 	    $req['data']['productid'] = 'DAJIN_GAME_Product'.$good_info['price'];//苹果产品ID
	    $req['data']['productid'] = 'DAJIN_GAME_Product30';//苹果产品ID
	    $req['data']['url'] = Config::get('GameDB.http').'/admin/recharge/pay/order?id='.$obj_order->orderID;//跳转链接
	    return json_encode($req);
	}
	
	/**
	 * 收单宝支付通知接口
	 */
	public function handleNotify(){
	    //获取 App 发送过来的数据,设置时候是沙盒状态
	    $data   = $_POST;
	    
	    try
	    {
	        $paykey = Config::get('Paykey');
	        
// 	        $sign = strtoupper(md5($paykey['key'] + $data['outTradeNo'] + $data['totalAmount'] + $data['tradeStatus']));
//             if($sign != $data['sign']){
//                 return false;
//             }
	        
	        $orderID = str_replace($paykey['merchant'], '', $data['outTradeNo']);//订单编号
	        
	        $order_info = YOnlineorder::get(['orderID'=>$orderID,'channel'=>2]);//订单详情
	        //订单编号
	        if(empty($order_info)){
	            return 'success';
	        }
	        //支付状态
	        if($data['tradeStatus'] != 'success'){
	            $order_info->status = 1;
	            if($order_info->save() === false){
	                throw new Exception('支付失败');
	            }
	            return 'success';
	        }
	        //金额不等
	        if(($order_info->orderamount) != $data['totalAmount']){
	            throw new Exception('金额不对');
	        }
	        if($order_info->getData('status') == 1){
	            return 'success';
	        }
	        if($order_info->getData('status') == 2){
	            return 'success';
	        }
	        
	        //添加房卡 并 修改订单信息 并 添加推广员提成
	        $obj = new YOnlineorder();
	        $obj->orderPay($orderID);
	        return 'success';
	    }
	    //捕获异常
	    catch(Exception $e)
	    {
	        Log::write('handleNotify:'.$data['outTradeNo'].$e->getMessage());
	        return $e->getMessage();
	    }
	}
	
	/**
	 * IOS支付后验证
	 */
	public function iosCheck(){
	    //获取 App 发送过来的数据,设置时候是沙盒状态
	    $receipt   = $_GET['data'];
        $receipt = str_replace(' ','+',$receipt);
    
	    $isSandbox = true;
	    //开始执行验证
	    try
	    {
	        $info = getReceiptData($receipt, $isSandbox);
	        //添加房卡 并 修改订单信息 并 添加推广员提成
	        $orderID   = $_GET['orderID'];//订单编号
	        $this->orderPay($orderID);
	        return resoK();
	    }
	    //捕获异常
	    catch(Exception $e)
	    {
	        Log::write('data:'.$receipt);
	        return resError($e->getMessage());
	    }
	}
	
	/**
	 * 分享绑定邀请码
	 * @author violet
	 * @since 2018-1-22
	 */
	public function loginCode()
	{
	    $data = $_POST;
	
	    //验证是否为空.
	    if(!isset($data))
	    {
	        return resError("参数不能为空");
	    }
	    if(!isset($data['headimgurl']))
	    {
	        return resError("headimgurl不能为空");
	    }
	    if(!isset($data['nickname']))
	    {
	        return resError("nickname不能为空");
	    }
	    if(!isset($data['sex']))
	    {
	        return resError("sex不能为空");
	    }
	    if(!isset($data['openid']))
	    {
	        return resError("openid不能为空");
	    }
	    if(!isset($data['unionid']))
	    {
	        return resError("unionid不能为空");
	    }
	    if(!isset($data['access_token']))
	    {
	        return resError("access_token不能为空");
	    }
	    if(!isset($data['code']))
	    {
	        return resError("code不能为空");
	    }
	    if(!isset($data['sign']))
	    {
	        return resError("sign不能为空");
	    }
	    $data['token'] = $data['access_token'];
	    
	    //签名验证
	    $agency_sign = strtoupper(md5($data['unionid'].$data['access_token'].$data['code'].$this->ApikeyConfig['Codekey']));  //与代理验证签名
	    if($data['sign'] != $agency_sign){
	        return resError('签名错误');
	    }

	    //发送给游戏服务器
	    if(Http::get($this->GameDBConfig['api_url'].'bindInvitationCode',$data) != 'ok' )
	    {
	        Log::write('loginCode:游戏服务器返回不等ok');
	        return resError('绑定邀请码失败');
	    }
	
	    return resoK();
	}

}